using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Windows.Forms;

namespace monitorMC
{
    public partial class Form1 : Form
    {

        string[] gameList =
        {
            "java",
            "javaw",
            "TslGame",
            "GTA5"
        };

        TimeSpan playTime = new TimeSpan(1, 0, 0);
        TimeSpan restTime = new TimeSpan(0, 40, 0);
        TimeSpan limitTime = new TimeSpan(0, 5, 0);
        TimeSpan totalPlayTime = new TimeSpan(0, 0, 0);
        Stopwatch swplay = new Stopwatch();
        Stopwatch swrest = new Stopwatch();

        int gameFreq = 0;

        bool flag = true;
        bool reminder = true;
        bool flag2 = true; //only execute once if time's up

        int originalSizeX = 0;
        int originalSizeY = 0;
        int fullSizeX = SystemInformation.PrimaryMonitorSize.Width / 2;
        int fullSizeY = SystemInformation.PrimaryMonitorSize.Height / 2;

        string today = DateTime.Now.ToString(@"yyyy-MM-dd");
        string path = AppDomain.CurrentDomain.BaseDirectory;
        string curGame;

        public Form1()
        {
            InitializeComponent();
        }

        //定时监测
        private void timer1_Tick(object sender, EventArgs e)
        {
            DateTime nowTime = DateTime.Now;
            curTime.Text = nowTime.ToString(@"G");


            //检测后台程序
            //javaw是hmcl
            //java是mc
            //Process[] javaw = Process.GetProcessesByName("javaw");
            //Process[] java = Process.GetProcessesByName("java");
            Process[] processes = Process.GetProcesses();
            bool inGame = false;

            //showPro();
            foreach (string game in gameList)
            {
                Process[] games = Process.GetProcessesByName(game);
                if (games.Length > 0)
                {
                    inGame = true;
                    switch (game)
                    {
                        case "java":
                        case "javaw":
                            curGame = "Minecraft";
                            break;
                        case "TslGame":
                            curGame = "PUBG";
                            break;
                        default:
                            curGame = game;
                            break;
                    }
                }
            }

            if (inGame)//在游戏中
            {
                try
                {
                    progressBar.Value = (int)(100 * swplay.Elapsed.Ticks / playTime.Ticks);
                }
                catch (ArgumentOutOfRangeException)
                {
                    progressBar.Value = 100;
                }
                catch (Exception ex)
                {

                }
                if (flag)
                {
                    swplay.Start();
                    swrest.Stop();
                    flag = false;
                    reminder = true;
                    label4.Text = "当前游戏：" + curGame;

                    //writeLog();
                }
            }
            else
            {
                try
                {
                    progressBar.Value = (int)(100 * swrest.Elapsed.Ticks / restTime.Ticks);
                }
                catch (ArgumentOutOfRangeException)
                {
                    progressBar.Value = 100;
                }
                catch (Exception ex)
                {
                }
                if (!flag)
                {
                    swplay.Stop();
                    swrest.Start();
                    flag = true;
                    label4.Text = "停止游戏";
                }
            }

            //判断是否超时
            if (TimeSpan.Compare(swplay.Elapsed, playTime) == 1 && flag2)
            {
                this.Show();
                flag2 = false;
                if (!flag) MessageBox.Show("时间到啦！\n不能玩啦！", "超时提醒", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);

                killMC();
                maxWindowState();

                swplay.Stop();
                swplay.Reset();

                //totalPlayTime += playTime;

                string path = AppDomain.CurrentDomain.BaseDirectory;
                File.AppendAllText($"{path}log/{today}.log", $"[INFO]{nowTime} PATH:{path}\n[INFO]{nowTime} 时间到，停止游戏\n");
            }
            else if ((TimeSpan.Compare(playTime - swplay.Elapsed, limitTime) == -1) && reminder)
            {
                reminder = false;
                MessageBox.Show("只能玩5分钟了哦\n5分钟后自动关闭", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
            }
            else if (TimeSpan.Compare(swrest.Elapsed, restTime) == 1)
            {
                this.Show();
                flag2 = true;
                if (flag) MessageBox.Show("休息够了！可以玩啦", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);

                recoverWindowState();

                File.AppendAllText($"{path}log/{today}.log", $"[INFO]{nowTime} PATH:{path}\n[INFO]{nowTime} rest time up\n");

                swplay.Reset();//重置游戏计时器
                swrest.Stop();
                swrest.Reset();//重置休息计时器
                gameFreq += 1;
                gamefreq.Text = gameFreq.ToString();
            }

            //显示游戏时间
            playLabel.Text = swplay.Elapsed.ToString(@"hh\:mm\:ss");
            restLabel.Text = swrest.Elapsed.ToString(@"hh\:mm\:ss");
            totalPlayLabel.Text = totalPlayTime.ToString(@"hh\:mm\:ss");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            int xWidth = SystemInformation.PrimaryMonitorSize.Width;//获取显示器屏幕宽度
            int yHeight = SystemInformation.PrimaryMonitorSize.Height;
            this.Location = new Point(xWidth - 1200, yHeight - 900);

            originalSizeX = this.Width;
            originalSizeY = this.Height;

            timer1.Start();
            timer2.Start();
            showPro();
            loginBtn.Hide();
            label4.Text = "未检测到游戏";

            if (!Directory.Exists(path + "log"))
            {
                Directory.CreateDirectory(path + "log");
            }

            File.AppendAllText($"{path}log/{today}.log", $"[INFO][BEGIN]{DateTime.Now.ToString($"G")} Program start.\n");
            writeLog();
            deleteLog();

        }

        private void formclosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.Visible)
            {
                this.Hide();
            }
            else
            {
                this.Show();
            }
        }

        private void exitDoubleclick(object sender, EventArgs e)
        {
            this.Close();
        }

        private void maxWindowState()
        {

            this.WindowState = FormWindowState.Maximized;//窗口最大化
            this.Show();
            this.TopMost = true;//窗口置顶
            this.BackColor = Color.PaleGreen;//变绿
            this.FormBorderStyle = FormBorderStyle.None;
        }

        private void killMC()
        {
            try
            {
                foreach (string game in gameList)
                {
                    Process[] mcs = Process.GetProcessesByName(game);//杀mc线程
                    foreach (Process mc in mcs)
                    {
                        mc.Kill();
                    };
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "把这段话拍给我，微信发过来");
            }
            //Process[] hmcl = Process.GetProcessesByName("javaw");//杀hmcl线程
            //if (hmcl.Length != 0) hmcl[0].Kill();
        }

        private void recoverWindowState()
        {
            this.WindowState = FormWindowState.Normal;//取消窗口最大化
            this.TopMost = false;//取消窗口置顶
            this.BackColor = Color.White;//变白
            this.FormBorderStyle = FormBorderStyle.Fixed3D;
        }

        private void writeLog() //把进程记录一下 其实没啥用
        {
            Process[] processes = Process.GetProcesses();
            File.AppendAllText($"{path}log/{today}.log", $"[INFO][Time:{DateTime.Now.ToString("T")}]Processes:");
            foreach (Process process in processes)
            {
                File.AppendAllText($"{path}log/{today}.log", $"[INFO][PROCESS] 进程名称：{process.ProcessName}\n");
                File.AppendAllText($"{path}log/{today}.log", $"[INFO][PROCESS] 进程ID：{process.Id}\n");
            }
        }

        private void showPro() //把进程记录一下 其实没啥用
        {
            listBox1.Items.Clear();
            Process[] processes = Process.GetProcesses();
            foreach (Process process in processes)
            {
                listBox1.Items.Add($"{process.ProcessName}\n");
            }
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void menu_enter(object sender, EventArgs e)
        {
            if (toolStripTextBox2.Text == "1")
            {
                Process curPro = Process.GetCurrentProcess();
                MessageBox.Show(curPro.ProcessName);
            }
        }

        private void loginBtn_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
            this.Close();
            form2.ShowDialog();
        }

        bool isOpen = false;
        private void open_Click(object sender, EventArgs e)
        {
            if (!isOpen)
            {
                open.Text = "收回数据";
                isOpen = true;
                this.Width = fullSizeX;
                this.Height = fullSizeY;
            }
            else
            {
                open.Text = "展开数据";
                isOpen = false;
                this.Width = originalSizeX;
                this.Height = originalSizeY;
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            writeLog();
            showPro();
        }

        private void deleteLog()
        {
            string logDirectory = Path.Combine(path, "log");
            string[] logs = Directory.GetFiles(logDirectory);

            foreach (string log in logs)
            {
                try
                {
                    string fileName = Path.GetFileNameWithoutExtension(log); // 直接获取无扩展名的文件名
                    DateTime dt;

                    // 尝试解析两种日期格式
                    if (DateTime.TryParseExact(fileName, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt) ||
                        DateTime.TryParseExact(fileName, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
                    {
                        TimeSpan ts = DateTime.Now - dt;
                        if (ts.Days > 100)
                        {
                            File.Delete(log);
                        }
                    }
                    else
                    {
                        // 日期解析失败，记录错误
                        File.AppendAllText($"{logDirectory}/{today}.log", $"[ERROR][FILE] 无法解析日期：{fileName}\n");
                    }
                }
                catch (Exception ex)
                {
                    File.AppendAllText($"{logDirectory}/{today}.log", $"[ERROR][FILE] 删除失败：{log}\n");
                    File.AppendAllText($"{logDirectory}/{today}.log", $"[ERROR][FILE] {ex}\n");
                }
            }
        }

        //private void btn1Click(object sender, MouseEventArgs e)
        //{
        //    MessageBox.Show(toolStripTextBox2.Text);
        //}
    }
}
